package com.ruoyi.hiscomm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.hiscomm.domain.DrugBasicInfoDo;
import com.ruoyi.hiscomm.request.DrugParm;
import com.ruoyi.hiscomm.service.IDrugBasicInfoService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ruoyi.common.core.utils.ListPaginator.getTotalPages;
import static com.ruoyi.common.core.utils.ListPaginator.paginate;

/**
 * @ClassName DrugBasicInfoController
 * @Author samula
 * @Descripe product by com.doctcloud
 * @Data 2025-10-03 16:21
 **/
@RestController
@RequestMapping("/drugBasicInfoCtl")
public class DrugBasicInfoController extends BaseController {
    @Resource
    private IDrugBasicInfoService drugService;

    @PostMapping("add")
    public AjaxResult add(@RequestBody DrugBasicInfoDo drug) throws IOException {
        String error = checkObjectValid(drug);
        if (error.length() > 0){
            return error(error);
        }
        if (drugService.checkDrugUnique(drug))
        {
            return error("新增药品'" + drug.getDrugName() + "',通过唯一码、通用名编码、规格、厂家 唯一性 验证失败，药品已存在");
        }
        drug.setValidInd(1);
        drug.setCreateDate(new Date());
        int i = drugService.insertDrugBasicInfo(drug);
        return toAjax(i);
    }
    @PutMapping("update")
    public AjaxResult update(@RequestBody DrugBasicInfoDo drug) throws IOException {
        String error = checkObjectValid(drug);
        if (error.length() > 0){
            return AjaxResult.error(error);
        }
        return toAjax(drugService.updateDrugBasicInfo(drug));
    }
    @DeleteMapping("delete")
    public AjaxResult delete(@RequestBody DrugBasicInfoDo drug) throws IOException {
        if (ObjectUtils.isEmpty(drug)){
            return AjaxResult.error("删除的药品信息无效");
        }
        if (StringUtils.isEmpty(drug.getDrugStdCode())){
            return AjaxResult.error("删除的药品信息提供缺失药品唯一码信息");
        }
        return toAjax(drugService.deleteDrugBasicInfo(drug));
    }
    @GetMapping("list")
    @ResponseBody
    public TableDataInfo list(){
        List<DrugBasicInfoDo> list = drugService.listDrugBasicInfos();
        return getDataTable(list);
    }
    @GetMapping("RpageList")
    public AjaxResult rlistPage(@RequestBody DrugParm parm){
        IPage<DrugBasicInfoDo> resultPage = drugService.pageRedisDeptList(parm);
        return AjaxResult.success(resultPage);
    }
    @GetMapping("pageList")
    public AjaxResult listPage(@RequestBody DrugParm parm) {
        // 防御性校验：确保parm不为null
        if (parm == null) {
            parm = new DrugParm();
        }
        // 处理分页参数默认值（已确保非null）
        int currentPage = parm.getCurrentPage() == null || parm.getCurrentPage() < 1
                ? 1
                : parm.getCurrentPage();
        int pageSize = parm.getPageSize() == null || parm.getPageSize() < 1
                ? 10
                : parm.getPageSize();
        // 限制最大页大小，避免一次性查询过多数据
        pageSize = Math.min(pageSize, 100);
        IPage<DrugBasicInfoDo> resultPage = new Page<>(currentPage, pageSize);
        // 无搜索词时，从缓存/数据库查询
        if (StringUtils.isEmpty(parm.getDrugName())) {
            List<DrugBasicInfoDo> allDrugs = drugService.listDrugBasicInfos();
            allDrugs = allDrugs == null ? new ArrayList<>() : allDrugs; // 防止null
            int total = allDrugs.size();
            resultPage.setTotal(total);
            resultPage.setPages(getTotalPages(allDrugs, pageSize)); // 使用处理后的pageSize
            resultPage.setRecords(paginate(allDrugs, currentPage, pageSize)); // 使用处理后的参数
        } else {
            // 有搜索词时，调用ES分页查询
            IPage<DrugBasicInfoDo> esPage = drugService.pageESDrugList(parm);
            resultPage = esPage != null ? esPage : resultPage; // 防御性处理
        }
        return AjaxResult.success(resultPage);
    }

    private String checkObjectValid(DrugBasicInfoDo drug){
        String res = "";
        if (StringUtils.isEmpty(drug.getDrugStdCode())) {
            return "药品唯一码不得为空";
        }
        if (StringUtils.isEmpty(drug.getDrugSpec())){
            return "药品规格不得为空";
        }
        if (StringUtils.isEmpty(drug.getDrugCode())){
            return "药品通用名代码不得为空";
        }
        if (StringUtils.isEmpty(drug.getDrugName())){
            return "药品通用名不得为空";
        }
        if (StringUtils.isEmpty(drug.getDrugUnit())){
            return "药品最小单位不得为空";
        }
        if (StringUtils.isEmpty(drug.getFirmId())){
            return "药品厂家不得为空";
        }
        if (StringUtils.isEmpty(drug.getDoseUnit())){
            return "药品最小使用剂量单位不得为空";
        }
        if (StringUtils.isEmpty(drug.getMinPackUnit())){
            return "药品流通包装单位不得为空";
        }
        if (ObjectUtils.isEmpty(drug.getMinPack()) || drug.getMinPack() <= 0){
            return "药品流通包装不得为空或小于等于零";
        }
        if (ObjectUtils.isEmpty(drug.getDosePerUnit()) || drug.getDosePerUnit() <= 0.0){
            return "药品最小使用剂量不得为空或小于等于零";
        }
        return res;
    }
}
